package cn.zyjw.service.impl;

import cn.zyjw.service.SysPrivilegeService;
import cn.zyjw.service.SysRolePrivilegeService;
import cn.zyjw.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zyjw.domain.SysMenu;
import cn.zyjw.mapper.SysMenuMapper;
import cn.zyjw.service.SysMenuService;
import org.springframework.util.CollectionUtils;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPrivilegeService sysPrivilegeService;

    /**
     * 根据用户id获取菜单数据
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        //1 判断用户是否为超级管理员
        if (sysRoleService.isSuperAmdin(userId)) {
            return list();
        } else {
            // 2 如果不是超级管理员 返回拥有角色对应的 菜单
            return this.baseMapper.selectMenusByUserId(userId);
        }
    }

    /**
     * 查询角色权限配置列表
     *
     * @param roleId
     * @return
     */
    @Override
    public List<SysMenu> findRolePrivilegesList(Long roleId) {
        List<SysMenu> menuList = list();
        if (CollectionUtils.isEmpty(menuList)) {
            return Collections.emptyList();
        }
        List<SysMenu> rootMenus = menuList.stream()
                .filter(menu -> menu.getParentId() == null)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(rootMenus)) {
            return Collections.emptyList();
        }

        List<SysMenu> sysMenus = new ArrayList<>();
        for (SysMenu rootMenu : rootMenus) {
            sysMenus.addAll(getChildMenus(rootMenu.getId(), roleId, menuList));

        }
        return sysMenus;
    }

    /**
     * 获得子菜单及子菜单的权限
     *
     * @param id
     * @param roleId
     * @param menuList
     */
    private List<SysMenu> getChildMenus(Long id, Long roleId, List<SysMenu> menuList) {
        List<SysMenu> childs = new ArrayList<>();
        for (SysMenu sysMenu : menuList) {
            if (sysMenu.getParentId() != null && sysMenu.getParentId().equals(id)) {
                sysMenu.setChilds(getChildMenus(sysMenu.getId(), roleId, menuList));
                sysMenu.setPrivileges(sysPrivilegeService.getPrivileges(sysMenu.getId(),roleId));
                childs.add(sysMenu);
            }
        }
        return childs;
    }
}
